<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.04.10
 */

namespace App\Service;

use App\Library\Clog\Log;
use Exception;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;

class AliyunEcs
{
    /**
     * 发起请求
     *
     * @param string $method $method
     * @param string $loadBalancerId $loadBalancerId
     * @param string $regionId $regionId
     * @param string $listenerPort $listenerPort
     * @throws ClientException
     * @throws Exception
     * @throws Exception
     * @return array
     */
    public static function requestApi($method, $loadBalancerId, $regionId, $listenerPort = '')
    {
        if (!$method) {
            $method = 'DescribeHealthStatus';
        }

        if (empty(env('ALIYUN_SLB_APPID')) || empty(env('ALIYUN_SLB_APP_SECRET'))) {
            throw new \ErrorException("请在env中配置阿里云SLB信息");
        }

        AlibabaCloud::accessKeyClient(env('ALIYUN_SLB_APPID'), env('ALIYUN_SLB_APP_SECRET'))
            ->regionId($regionId)
            ->asGlobalClient();

        try {
            $query = [
                'RegionId'       => $regionId,
                'LoadBalancerId' => $loadBalancerId,
            ];
            if ($listenerPort) {
                $query['ListenerPort'] = $listenerPort;
            }
            $result = AlibabaCloud::rpc()
                ->product('Slb')
                ->version('2014-05-15')
                ->action($method)
                ->host('slb.aliyuncs.com')
                ->options([
                    'query' => $query,
                ])
                ->request()->toArray();

            Log::info('AliyunEcsService', 'aliyunPort', [$result]);

            return $result;

        } catch (Exception $exception) {
            Log::exception($exception);
            throw new Exception(t('message.12047'));
        }
    }
}
